package com.cy.pj.common.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存切面
 */
@Order(1)
@Aspect
@Component
public class SysCacheAspect {

    private Map<String,Object> cache = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
    public void doCache(){}

    @Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
    public void doClearCache(){}

    @AfterReturning("doClearCache()")
    public void doClearAround(){
        cache.clear();
    }

    @Around("doCache()")
    public Object doAround(ProceedingJoinPoint joinPoint)throws Throwable{
        System.out.println("Get data from cache");
        Object result = cache.get("deptkey");//这里的key先用一个固定值
        if (result!=null) return result;
        result = joinPoint.proceed();
        System.out.println("Put data from cache");
        cache.put("deptkey", result);
        return result;
    }
}
